package com.scs.application.modules.cfg.utils;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONArray;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.consts.ParamKeys;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UtilCommon;
import com.scs.application.modules.base.dto.MatrEditConfigDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.StreamSupport;

/**
 * 配置文件
 */
@Slf4j
@Component
public class ParameterUtils implements InitializingBean {

    private final static Properties props = new Properties();

    @Autowired
    private Environment environment;


    /**
     * 获取工程路径
     *
     * @return
     */
    public static String getProjectPath() {
        // 如果配置了工程路径，则直接返回，否则自动获取。
        String projectPath = getString("projectPath");
        if (StringUtils.isNotBlank(projectPath)) {
            return projectPath;
        }
        try {
            File file = new DefaultResourceLoader().getResource("").getFile();
            if (file != null) {
                while (true) {
                    File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
                    if (f == null || f.exists()) {
                        break;
                    }
                    if (file.getParentFile() != null) {
                        file = file.getParentFile();
                    } else {
                        break;
                    }
                }
                projectPath = file.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return projectPath;
    }

    public static String getString(String key, String defaultValue) {
        return (String) props.getOrDefault(key, defaultValue);
    }

    public static String getString(String key) {
        return getString(key, null);
    }

    public static boolean getBoolean(String key, boolean defualtValue) {
        String value = getString(key);
        if (StringUtils.isBlank(value)) {
            return defualtValue;
        }
        return GlobalConsts.YES_STR.equalsIgnoreCase(value);
    }

    public static boolean getBoolean(String key) {
        return getBoolean(key, false);
    }

    public static int getInt(String key, int defaultValue) {
        return Integer.valueOf(props.getOrDefault(key, defaultValue)+"");
    }

    public static void put(String key, Object value) {
        props.put(key, value);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        /**
         * 从环境变量中加载配置参数
         */
        MutablePropertySources propSrcs = ((AbstractEnvironment) environment).getPropertySources();
        StreamSupport.stream(propSrcs.spliterator(), false)
                .filter(ps -> ps instanceof OriginTrackedMapPropertySource)
                .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
                .flatMap(Arrays::<String>stream)
                .forEach(propName -> props.setProperty(propName, environment.getProperty(propName)));

    }

    public static boolean isAllowOverApply() {
        return ParameterUtils.getBoolean(ParamKeys.ALLOW_OVER_APPLY, true);
    }

    public static boolean isAllowOverDemand() {
        return ParameterUtils.getBoolean(ParamKeys.ALLOW_OVER_DEMAND, false);
    }

    public static boolean isApplyLockStock() {
        return ParameterUtils.getBoolean(ParamKeys.FLAG_APPLY_LOCK, true);
    }

    /**
     * 入库单自动转配送单
     *
     * @return
     */
    public static boolean isAutoChangeDist() {
        return ParameterUtils.getBoolean(ParamKeys.AUTO_CHANGE_DIST, false);
    }

    /**
     * 入库单自动转调拨单
     *
     * @return
     */
    public static boolean isAutoChangeTransfer() {
        return ParameterUtils.getBoolean(ParamKeys.AUTO_CHANGE_TRANSFER, false);
    }

    /**
     * 入库单允许修改
     *
     * @return
     */
    public static boolean isAllowInOrderModify() {
        return ParameterUtils.getBoolean(ParamKeys.ALLOW_IN_ORDER_MODIFY, false);
    }

    /**
     * 是否上线第一次使用
     * @return
     */
    public static boolean getFlagisFirstUse() {
        return ParameterUtils.getBoolean(ParamKeys.FLAG_IS_FIRSTUSE, false);
    }

    /**
     * 入库单允许删除
     *
     * @return
     */
    public static boolean isAllowInOrderDelete() {
        return ParameterUtils.getBoolean(ParamKeys.ALLOW_IN_ORDER_DELETE, false);
    }

    /**
     * 采购单是否整包装发货
     *
     * @return
     */
    public static boolean flagWhole() {
        return ParameterUtils.getBoolean(ParamKeys.FLAG_WHOLE, true);
    }

    /**
     * 是否请领转需求后直接审核通过
     *
     * @return
     */
    public static boolean isApplyDemandAudit() {
        return ParameterUtils.getBoolean(ParamKeys.APPLY_DEMAND_AUDIT, false);
    }

    /**
     * 是否执行科室与消耗科室一致
     *
     * @return
     */
    public static boolean isHisBillDept() {
        return ParameterUtils.getBoolean(ParamKeys.HIS_BILL_DEPT, false);
    }

    /**
     * 系统以HIS科室为准计费   还是 系统以HRP科室为准计费
     *
     * @return
     */
    public static boolean isHisOrHrpMap() {
        return ParameterUtils.getBoolean(ParamKeys.IS_HIS_OR_HRP, false);
    }

    /**
     * 获取超级密码
     *
     * @return
     */
    public static String getSuperPassword() {
        return ParameterUtils.getString(ParamKeys.SUPER_PASSWORD);
    }

    /**
     * 科室请领是否挂单
     *
     * @return
     */
    public static boolean isApplyHolder() {
        return ParameterUtils.getBoolean(ParamKeys.APPLY_HOLDER, false);
    }


    public static String getTemporaryPurchaseNum() {
        return ParameterUtils.getString(ParamKeys.TEMPORARY_PURCHASE_NUM, "4");
    }

    /**
     * 是否允许访问公网
     *
     * @return
     */
    public static boolean isAllowInternet() {
        return ParameterUtils.getBoolean(ParamKeys.SYSTEM_ALLOW_INTERNET, true);
    }

    /**
     * 单条入库明细最大包装数量
     */
    public static String getSystemInPackageMax() {
        return ParameterUtils.getString(ParamKeys.SYSTEM_IN_PACKAGE_MAX, "1000");
    }

    /**
     * 结算流程字段筛选字段值
     */
    public static String getSystemSettlementFlowValue() {
        return ParameterUtils.getString(ParamKeys.SYSTEM_SETTLEMENT_FLOW_VALUE, "end");
    }

    /**
     * his查询和计费接口是否使用xml true:使用
     *
     * @return
     */
    public static boolean isHisByXML() {
        return ParameterUtils.getBoolean(ParamKeys.IS_HIS_BY_XML, false);
    }


    /**
     * @Description：his相关同步使用 webservice 的方法列表
     */
    public static List getHisSyncWSFuns() {
        String param = ParameterUtils.getString(ParamKeys.HIS_SYNC_WS_FUNS, "");
        if (StringUtils.isBlank(param)) return Arrays.asList("-1");
        return Arrays.asList(param.split(","));
    }

    /**
     * @Description：his 数据 webservice 地址
     */
    public static String getHisSyncWSAddr() {
        return ParameterUtils.getString(ParamKeys.HIS_SYNC_WS_ADDR, "");
    }


    /**
     * @Description：his webservice  授权信息
     */
    public static String getHisWSAuth() {
        return ParameterUtils.getString(ParamKeys.HIS_SYNC_WS_AUTH, "");
    }

    /**
     * @Description：his webservice  授权信息
     * [{"supplierName":"供应商","pkname":"supplierName","flagEnabled":"1","flagUpdateStock":"0"}]
     */
    public static Map<String, MatrEditConfigDTO> matrEditConfig() {
        String matrEditConfig = ParameterUtils.getString(ParamKeys.MATR_EDIT_CONFIG, "");
        if (StringUtils.isBlank(matrEditConfig)) return null;
        List<MatrEditConfigDTO> matrEditConfigDTOList = JSONArray.parseArray(matrEditConfig, MatrEditConfigDTO.class);
        if (matrEditConfigDTOList == null) return null;
        Map<String, MatrEditConfigDTO> matrEditConfigDTOMap = new HashMap<String, MatrEditConfigDTO>();
        matrEditConfigDTOList.forEach(matrEditConfigDTO -> matrEditConfigDTOMap.put(matrEditConfigDTO.getPkname(), matrEditConfigDTO));
        return matrEditConfigDTOMap;
    }

    /**
     * @Description：his webservice  授权信息
     * [{"supplierName":"供应商","pkname":"supplierName","flagEnabled":"1","flagUpdateStock":"0"}]
     */
    public static List<MatrEditConfigDTO> matrEditConfigList() {
        String matrEditConfig = ParameterUtils.getString(ParamKeys.MATR_EDIT_CONFIG, "");
        if (StringUtils.isBlank(matrEditConfig)) return null;
        List<MatrEditConfigDTO> matrEditConfigDTOList = JSONArray.parseArray(matrEditConfig, MatrEditConfigDTO.class);
        return matrEditConfigDTOList;
    }

    /**
     * @Description：单点登录CAS服务服务端校验地址
     */
    public static String getCasServiceValidateUrl() {
        return ParameterUtils.getString(ParamKeys.CSA_SERVICE_VALIDATE_URL, "");
    }

    /**
     * @Description：单点登录CAS服务客户端接收地址
     */
    public static String getCasServiceClientUrl() {
        return ParameterUtils.getString(ParamKeys.CSA_SERVICE_CLIENT_URL, "");
    }

    /**
     * HRP的库存视图   true:使用
     *
     * @return
     */
    public static boolean isStockcheckUseview() {
        return ParameterUtils.getBoolean(ParamKeys.STOCKCHECK_USEVIEW, false);
    }

    /**
     * @Description：配送拣货查找库存排序方式,默认1 dist_stock_priority;
     */
    public static String getDistStockPriority() {
        return ParameterUtils.getString(ParamKeys.DIST_STOCK_PRIORITY, "1");
    }

    /**
     * @Description：响应需求是否自动拣货 flag_auto_pick
     */
    public static boolean getFlagAutoPick() {
        return ParameterUtils.getBoolean(ParamKeys.FLAG_AUTO_PICK, false);
    }

    /**
     * 外部打印是否直接打印 1:直接打印
     *
     * @return
     */
    public static boolean isSpdAmsPrintDirect() {
        return ParameterUtils.getBoolean(ParamKeys.SPDAMS_PRINT_DIRECT, false);
    }

    /**
     *
     *  是否显示耗材型号，1显示 0不显示
     *
     * @return
     */
    public static boolean isShowMatrModel() {
        return ParameterUtils.getBoolean(ParamKeys.SHOW_MATR_MODEL, true);
    }


    /**
     * @Description： HRP相关参数
     */
    public static class Hrp{
        /**
         * HRP同步耗材过滤条件 不包含where,如：matr_code LIKE '09%'
         */
        public static String getMatrListFilter() {
            String sqlFilter = ParameterUtils.getString(ParamKeys.Hrp.getMatrListFilter, "");
            if (StringUtils.isBlank(sqlFilter)) return "";
            return " where "+ sqlFilter;
        }
    }



    /**
     * @Description： spd相关参数
     */
    public static class spd{
        /**
         * HRP同步耗材过滤条件 不包含where,如：matr_code LIKE '09%'
         */
        public static String getBudgetControlType() {
            return ParameterUtils.getString(ParamKeys.Spd.BUDGET_CONTROL_TYPE, "0");
        }

        /**
         * 允许发货后关闭
         */
        public static int getAllowCloseAfterDelivered() {
            return ParameterUtils.getInt(ParamKeys.Spd.ALLOW_CLOSE_AFTER_DELIVERED, 1);
        }
    }

    public static boolean getFlagStockCheck() {
        return ParameterUtils.getBoolean(ParamKeys.FLAG_STOCK_CHECK, true);
    }

    /**
     * @Description：系统数据库备份路径
     */
    public static String getSystemDbbackPath() {
        return ParameterUtils.getString(ParamKeys.SYSTEM_DBBACK_PATH, "");
    }


    /**
     * @Description：上线第一个结算周期的期末库存,历史表必须要数据
     */
    public static String getStockSettlementPush() {
        return ParameterUtils.getString(ParamKeys.STOCK_SETTLEMENT_PUSH, "0");
    }

    /**
     * RFID正则表达式
     * @return
     */
    public static String getRFIDRegex() {
        return ParameterUtils.getString(ParamKeys.RFID_REGEX, "RFID\\w*$|012\\d{20,21}$|FA\\d{21,22}$|(F4|04)\\d{9}$");
    }

    /**
     * 自动读取消息时限
     * @return
     */
    public static Integer getMsgAutoReadTime() {
        return ParameterUtils.getInt(ParamKeys.MSG_AUTO_READ_TIME, 7 * 24);
    }

    /**
     * @Description：是否使用his视图查询病人信息
    */
    public static boolean isPatientSelectHisView() {
        return ParameterUtils.getString(ParamKeys.PATIENT_SELECT_TYPE, "table").equalsIgnoreCase("his_view");
    }
    /**
     * @Description：供应商平台更新哪些商品字段
    */
    public static List<String> getScpMatrUpdateFields() {
        String get = ParameterUtils.getString(ParamKeys.scp_matr_update_fields, "");
        if (UtilCommon.strIsNull(get)) {
            return null;
        }
        return Arrays.asList(StringUtils.split(get, ","));
    }
}
